package com.sz.app.customer.api.trade;

import com.sz.biz.app.web.BaseController;
import com.sz.biz.common.constants.MessagesCodes;
import com.sz.biz.logistics.ord.entity.OrderDetail;
import com.sz.biz.trade.constants.TrdConstants;
import com.sz.biz.trade.ord.entity.TrdOrderDetail;
import com.sz.biz.trade.ord.entity.TrdOrderStatus;
import com.sz.biz.trade.ord.entity.TrdOrderType;
import com.sz.biz.trade.ord.service.TrdOrderConfirmationService;
import com.sz.biz.trade.ord.service.TrdOrderDeliveryService;
import com.sz.biz.trade.ord.service.TrdOrderService;
import com.sz.biz.trade.ord.dto.PathPDFDto;
import com.sz.biz.trade.ord.dto.TrdOrderDto;
import com.sz.biz.trade.ord.dto.TrdOrderInfoCustomerDto;
import com.sz.common.base.dto.CommonModel;
import com.sz.common.base.dto.QueryParams;
import com.sz.common.base.dto.ResultDto;
import com.sz.common.base.utils.DateUtils;
import com.sz.common.base.utils.StringUtils;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

/**
 * Function: 订单管理 <br>
 * Author: jifeixing <br>
 * Date: 2017-07-19 14:18:00
 */
@RestController
@RequestMapping("${api}/cust/trd/order")
@Api(description = " ", tags = "043、贸易-订单管理")
public class TrdOrderController extends BaseController {

    @Autowired
    private TrdOrderService trdOrderService;

    @Autowired
    private TrdOrderConfirmationService trdOrderConfirmationService;

    @Autowired
    private TrdOrderDeliveryService trdOrderDeliveryService;

    /**
     * 所有订单类型
     *
     * @return
     */
    @ApiOperation(value = "所有订单类型", notes = "所有订单类型")
    @RequestMapping(value = "/orderType", method = RequestMethod.GET)
    public ResultDto orderType() {
        List<CommonModel> list = trdOrderService.orderType();
        ResultDto result = new ResultDto();
        result.setData(list);
        return result;
    }

    /**
     * 所有订单状态
     *
     * @return
     */
    @ApiOperation(value = "所有订单状态", notes = "所有订单状态")
    @RequestMapping(value = "/orderStatus", method = RequestMethod.GET)
    public ResultDto orderStatus() {
        List<CommonModel> list = trdOrderService.orderStatus();
        ResultDto result = new ResultDto();
        result.setData(list);
        return result;
    }

    /**
     * 下单
     * @throws Exception
     */
    @ApiOperation(value = "下单", notes = "下单")
    @RequestMapping(value = "/save", method = {RequestMethod.POST})
    public ResultDto save(@RequestBody @ApiParam(value = "订单信息", required = true) @Validated TrdOrderDto trdOrderDto) throws ParseException {
        trdOrderDto.setOrderChannel(1);
        String orderNo = trdOrderService.saveForCustomer(trdOrderDto);
        ResultDto result = getSaveSuccessDto(MessagesCodes.MODULE_TRADE_ORDER);
        TrdOrderStatus statusTo = trdOrderDto.getOrderStatus();
        if(null == statusTo){
            result = saveDraftSuccessDto();
        }else if(statusTo.getCode().equals(TrdOrderStatus.CONFIRMING.getCode())){
            result = getOrderSubmitSuccessDto(MessagesCodes.MODULE_TRADE_ORDER);
        }
        result.setData(orderNo);
        return result;
    }

    /**
     * 根据订单号查询
     */
    @ApiOperation(value = "根据订单号查询", notes = "根据订单号查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNo", value = "订单编号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "customerType", value = "1: 客户； 2： 供应商", dataType = "string", paramType = "query")})
    @RequestMapping(value = "/orderNo", method = {RequestMethod.GET})
    public ResultDto findByOrderNo(@RequestParam(required = true) String orderNo, @RequestParam(required = true) String customerType) {
        TrdOrderInfoCustomerDto orderInfo;
        //销售订单（客户订单查询）
        if(customerType.equals(TrdOrderType.SALE.getCode())){
            orderInfo = trdOrderService.findByOrderNoCustomerSale(orderNo);
        }else{  //采购订单（供应商订单查询）
            orderInfo = trdOrderService.findByOrderNoCustomerPurchaser(orderNo);
        }
        ResultDto dto = new ResultDto();
        dto.setData(orderInfo);
        return dto;
    }

    /**
     * 根据订单号删除
     */
    @ApiOperation(value = "根据订单号删除", notes = "根据订单号删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNos", value = "订单号数组[]", required = true, dataType = "array", paramType = "body")})
    @RequestMapping(value = "/delete", method = {RequestMethod.POST})
    public ResultDto getGoodsById(@RequestBody List<String> orderNos) {
        trdOrderService.batchDeleteByOrderNos(orderNos, 1);
        return getDeleteSuccessDto(MessagesCodes.MODULE_TRADE_ORDER);
    }

    /**
     * 批量提交订单
     */
    @ApiOperation(value = "批量提交订单", notes = "批量提交订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNos", value = "订单号数组[]", required = true, dataType = "array", paramType = "body") })
    @RequestMapping(value = "/submit", method = { RequestMethod.POST })
    public ResultDto submit(@RequestBody List<String> orderNos) {
        trdOrderService.batchUpdateOrderStatus(orderNos, TrdOrderStatus.CONFIRMING);
        return getOrderSubmitSuccessDto(MessagesCodes.MODULE_TRADE_ORDER);
    }

    /**
     * 批量确认订单
     */
    @ApiOperation(value = "批量确认订单", notes = "批量确认订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNos", value = "订单号数组[]", required = true, dataType = "array", paramType = "body") })
    @RequestMapping(value = "/confirm", method = { RequestMethod.POST })
    public ResultDto confirm(@RequestBody List<String> orderNos) {
        trdOrderService.batchUpdateOrderStatus(orderNos, TrdOrderStatus.DELIVERY);
        return getConfirmationSuccessDto(MessagesCodes.MODULE_TRADE_ORDER);
    }

    /**
     * 批量发货
     */
    @ApiOperation(value = "批量发货", notes = "批量发货")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNos", value = "订单号数组[]", required = true, dataType = "array", paramType = "body") })
    @RequestMapping(value = "/delivery", method = { RequestMethod.POST })
    public ResultDto delivery(@RequestBody List<String> orderNos) {
        trdOrderService.batchUpdateOrderStatus(orderNos, TrdOrderStatus.TRANSPORT);
        return getDeliverySuccessDto(MessagesCodes.MODULE_TRADE_ORDER);
    }

    /**
     * 编辑订单
     *
     * @throws Exception
     */
    @ApiOperation(value = "编辑订单", notes = "编辑订单")
    @RequestMapping(value = "/update", method = {RequestMethod.POST})
    public ResultDto update(@RequestBody @ApiParam(value = "订单信息", required = true) @Validated TrdOrderDto trdOrderDto) throws ParseException {
        trdOrderService.update(trdOrderDto, 1);
        return this.getUpdateSuccessDto(MessagesCodes.MODULE_TRADE_ORDER);
    }

    /**
     * 客户订单列表
     */
    @ApiOperation(value = "客户订单列表", notes = "客户订单列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "q", value = "模糊查询参数", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "orderNo", value = "订单编号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "customerId", value = "客户id， 不区分供应商和客户", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "cusUserId", value = "当前登录用户", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "goodsId", value = "商品Id", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "goodsTypeId", value = "商品类型", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "创建起始时间(yyyy HH:mm:ss)", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "创建结束时间(yyyy HH:mm:ss)", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "orderStatus", value = "订单状态", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "pageIndex", value = "分页", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小，max2000", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "sort", value = "排序的字段", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "asc", value = "排序方式", dataType = "boolean", paramType = "query", defaultValue = "true")})
    @RequestMapping(value = "/list/sale", method = {RequestMethod.GET})
    public ResultDto orderListSale(@RequestParam(required = false) String q,
                                   @RequestParam(required = false) String orderNo,
                                   @RequestParam(required = false) String startTime,
                                   @RequestParam(required = false) String endTime,
                                   @RequestParam(required = false) Integer goodsTypeId,
                                   @RequestParam(required = false) Integer goodsId,
                                   @RequestParam(required = false) Integer customerId,
                                   @RequestParam(required = false) Integer cusUserId,
                                   @RequestParam(required = false) TrdOrderStatus orderStatus,
                                   @RequestParam(required = false, defaultValue = "1") int pageIndex,
                                   @RequestParam(required = false, defaultValue = "10") int pageSize,
                                   @RequestParam(required = false) String sort,
                                   @RequestParam(required = false, defaultValue = "true") Boolean asc) {
        q = StringUtils.replaceSqlPattern(q);
        QueryParams params = new QueryParams(pageSize, pageIndex, q, sort, asc);
        params.put("orderNo", orderNo);
        params.put("startTime", populateTime(startTime));
        params.put("endTime", populateTime(endTime));
        params.put("goodsTypeId", goodsTypeId);
        params.put("goodsId", goodsId);
        params.put("cusUserId", cusUserId);
        params.put("customerId", customerId);
        params.put("orderStatus", orderStatus);
        return trdOrderService.findByFilterCustomerSale(params);
    }

    /**
     * 供应商订单列表
     */
    @ApiOperation(value = "供应商订单列表", notes = "供应商订单列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "q", value = "模糊查询参数", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "orderNo", value = "订单编号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "customerId", value = "客户id， 不区分供应商和客户", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "cusUserId", value = "当前登录用户", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "goodsId", value = "商品Id", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "goodsTypeId", value = "商品类型", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "创建起始时间(yyyy HH:mm:ss)", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "创建结束时间(yyyy HH:mm:ss)", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "orderStatus", value = "订单状态", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "pageIndex", value = "分页", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小，max2000", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "sort", value = "排序的字段", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "asc", value = "排序方式", dataType = "boolean", paramType = "query", defaultValue = "true")})
    @RequestMapping(value = "/list/purchaser", method = {RequestMethod.GET})
    public ResultDto orderListPurchaser(@RequestParam(required = false) String q,
                                   @RequestParam(required = false) String orderNo,
                                   @RequestParam(required = false) String startTime,
                                   @RequestParam(required = false) String endTime,
                                   @RequestParam(required = false) Integer goodsTypeId,
                                   @RequestParam(required = false) Integer goodsId,
                                   @RequestParam(required = false) Integer customerId,
                                   @RequestParam(required = false) Integer cusUserId,
                                   @RequestParam(required = false) TrdOrderStatus orderStatus,
                                   @RequestParam(required = false, defaultValue = "1") int pageIndex,
                                   @RequestParam(required = false, defaultValue = "10") int pageSize,
                                   @RequestParam(required = false) String sort,
                                   @RequestParam(required = false, defaultValue = "true") Boolean asc) {
        q = StringUtils.replaceSqlPattern(q);
        QueryParams params = new QueryParams(pageSize, pageIndex, q, sort, asc);
        params.put("orderNo", orderNo);
        params.put("startTime", populateTime(startTime));
        params.put("endTime", populateTime(endTime));
        params.put("goodsTypeId", goodsTypeId);
        params.put("goodsId", goodsId);
        params.put("customerId", customerId);
        params.put("orderStatus", orderStatus);
        return trdOrderService.findByFilterCustomerPurchaser(params);
    }

    /**
     * 根据订单号导出pdf文件
     */
    @ApiOperation(value = "根据订单号导出pdf文件", notes = "根据订单号导出pdf文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNo", value = "订单号 ", required = true, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "type", value = "订单类型(1为订单确认单，2为订单收货单)", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/export/pdf/{orderNo}", method = {RequestMethod.GET})
    public ResultDto exportPDF(@PathVariable String orderNo, @RequestParam(required = true) String type) {
        PathPDFDto pathPDFDto;
        if (TrdConstants.OrderType.CONFIRM.equals(type)) {
            pathPDFDto = trdOrderConfirmationService.findPathByOrderNo(orderNo);
        } else {
            pathPDFDto = trdOrderDeliveryService.findPathByOrderNo(orderNo);
        }
        ResultDto dto = new ResultDto();
        if (pathPDFDto != null) {
            dto.setData(pathPDFDto.getPath());
        }
        return dto;
    }

    /**
     * 转换时间
     *
     * @param timeString
     * @return
     */
    private Date populateTime(String timeString) {
        Date date = null;
        try {
            if (!StringUtils.isEmpty(timeString)) {
                date = DateUtils.convertToDate(timeString, DateUtils.FORMAT_DETAIL);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return date;
    }

    @ApiOperation(value = "获取最新10条订单", notes = "获取最新10条订单<br>", httpMethod = "GET", position = 11)
    @RequestMapping(value = "/neworders", method = {RequestMethod.GET})
    public ResultDto getOrders() {
        List<TrdOrderDetail> trdOrderDetail = trdOrderService.getOrders();
        ResultDto result = new ResultDto();
        result.setData(trdOrderDetail);
        return result;
    }
}
